import { Router, NavigationGuardNext } from 'vue-router'
import { AutheUtils } from '@/utils'

class ExcludeHandler {

    protected excules: string[];

    private constructor(excules: string[]) {
        this.excules = excules;
    }

    public static create(excules: string[]) {
        return new ExcludeHandler(excules);
    }


    // 判断路由是否被忽略不拦截
    hasExclude(routerName: string): boolean {

        if (this.excules.indexOf(routerName) != -1) {
            return true
        }
        return false
    }

    toLoginPage(next: NavigationGuardNext, toRouteName?: string): void {

        let push: any = {
            name: "login"
        }

        if (toRouteName) {
            push.query = {
                to: toRouteName
            }
        }

        next(push)
    }


}

// 不被登录检测拦截的url
const eh = ExcludeHandler.create([
    "login",
    'qr-login'
]);


export function useAutheRouterHandler(router: Router) {

    // 检查是否登录并跳转至登录页
    router.beforeEach((to, from, next) => {
        if (AutheUtils.hasAuthed() || eh.hasExclude(<string>to.name)) {
            next()
        } else {
            eh.toLoginPage(next)
        }
    })

}

